package container.impl;

import container.Context;
import container.Wrapper;
import lifecycle.LifecycleBase;
import server.Servlet;

import java.util.Map;
import java.util.Set;

/**
 * @ClassName : StandContext
 * @Description : 11
 * @Author : zhangxiaohai
 * @Date: 2021-06-24 17:20
 */
public class StandContext extends LifecycleBase implements Context {
    private Map<String, Wrapper> wrapperMap = new java.util.concurrent.ConcurrentHashMap<>();
    private String contextName;
    private ClassLoader classLoader;

    @Override
    public void setContextName(String contextName) {
        this.contextName = contextName;
    }

    @Override
    public String getContextName() {
        return this.contextName;
    }

    @Override
    public void addWrapper(Wrapper wapper) {
        wrapperMap.put(wapper.getUrlPattern(), wapper);
    }

    @Override
    public Wrapper findWapper(String urlPattern) {
        return wrapperMap.get(urlPattern);
    }

    @Override
    public void setClassloader(ClassLoader classloader) {
        this.classLoader = classloader;
    }

    @Override
    protected void initInternal() throws Exception {
        // 保存 servlet 容器集合
        Set<Map.Entry<String, Wrapper>> entries = wrapperMap.entrySet();
        for (Map.Entry<String, Wrapper> entry : entries) {
            Wrapper value = entry.getValue();
            try {
                // 通过全限定类名获取到 servlet 类
                Class<?> aClass = this.classLoader.loadClass(value.getClassName());
                // 实例化 servlet
                Servlet servlet = (Servlet) aClass.newInstance();
                // 将 servlet 类实例设置到对应的 Wrapper 中
                value.setServlet(servlet);
                servlet.init();
                System.out.println(servlet.getClass().getName() + " init");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void startInternal() {
        System.out.println(this.getClass().getName() + " startContext");
    }
}
